package com.ljfiction.book.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.ljfiction.book.Baner.CreadChapterBookBean;
import com.ljfiction.book.Dialog.FabuzhangjieIsVIP;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.CreatChapterSettingManager;
import com.ljfiction.book.tools.EventTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class CreadChapterOkActivity extends BaseActivity {

    @BindView(R.id.deletthis)
    ImageView deletthis;
    @BindView(R.id.lijifabu)
    SuperButton lijifabu;
    @BindView(R.id.timingfabu)
    SuperButton timingfabu;

    private int isfabutype = 0;//0是创建发布，1是草稿发布
    private TimePickerDialog mDialogAll;
    private FabuzhangjieIsVIP fabuzhangjieIsVIPDialog;
    private CreadChapterBookBean bookBean;
    private int chapterIsVip = 0;
    private String chapter = "";
    private NoBackgLodDialog noBackgLodDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cread_chapter_ok);
        ButterKnife.bind(this);
        bookBean = (CreadChapterBookBean) getIntent().getSerializableExtra("bookBean");
        chapter = StringTool.getChapterText(bookBean.getChapterContent());
        if (bookBean.getWhereCome() == 0) {
            intView();
        }


    }

    private void intView() {
        fabuzhangjieIsVIPDialog = new FabuzhangjieIsVIP(this, bookBean.getBookisvip(), false);
        fabuzhangjieIsVIPDialog.setListener(new FabuzhangjieIsVIP.Listener() {
            @Override
            public void okClick(int isVip) {
                chapterIsVip = isVip;
            }

            @Override
            public void isOkClick() {
                showToast("这本书还没有上架，快去申请上架吧！");
            }

            @Override
            public void isdelect() {
                goBack();
            }
        });
    }

    @OnClick({R.id.deletthis, R.id.lijifabu, R.id.timingfabu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.deletthis:
                goBack();
                break;
            case R.id.lijifabu:
                if (bookBean.getWhereCome()==1){
                    toupdate(TimeTool.getThistime());
                }else if (bookBean.getIsCaogao() == 0) {
                    tofabu(TimeTool.getThistime());
                } else {
                    caogaofabu(TimeTool.getThistime());
                }

                break;
            case R.id.timingfabu:
                if (bookBean.getReleastime() < System.currentTimeMillis() + 180000 && bookBean.getWhereCome() == 1) {
                    showToast("亲，只有定时发布的章节，并且定时的时间在三分钟之后的才可以修改哦");
                    return;
                }
                mDialogAll = new TimePickerDialog.Builder()
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date date = new Date(millseconds);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                if (bookBean.getWhereCome()==1){
                                    toupdate(format.format(date));
                                } else if (bookBean.getIsCaogao() == 0) {
                                    tofabu(format.format(date));
                                } else {
                                    caogaofabu(format.format(date));
                                }

                            }
                        })
                        .setCancelStringId("取消")
                        .setSureStringId("发布")
                        .setTitleStringId("选择时间")
                        .setYearText("年")
                        .setMonthText("月")
                        .setDayText("日")
                        .setHourText("时")
                        .setMinuteText("分")
                        .setCyclic(false)
                        .setMinMillseconds(System.currentTimeMillis())
                        .setMaxMillseconds(System.currentTimeMillis() + Long.valueOf("642816000000"))
                        .setCurrentMillseconds(System.currentTimeMillis())
                        .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                        .setType(Type.ALL)
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                        .setWheelItemTextSize(12)
                        .build();
                mDialogAll.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
        }
    }

    private void toupdate(String time) {
        if (!UserManageBean.isLogin(CreadChapterOkActivity.this)) {
            return;
        }
        OkHttpUtils.post(HttpManager.IP + "/chapter-update")

                .params("chapterTitle", bookBean.getChapterTitle())
                .params("bookId", bookBean.getBookId())
                .params("chapterContent", chapter)
                .params("chapterLength", StringTool.getChapterTextLength(chapter))
                .params("volumeId", bookBean.getVolumeId())
                .params("whetherPublic", "0")
                .params("releaseTime", time)
                .params("id", bookBean.getId())
                .params("authorWords", bookBean.getAuthorWords())
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog == null) {
                            noBackgLodDialog = new NoBackgLodDialog(CreadChapterOkActivity.this, true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        noBackgLodDialog.dismis();
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                setResult(2);
                                goBack();
                            }else if (js.getInt("returnCode") == 400){
                                Intent intent3=new Intent(CreadChapterOkActivity.this,LoginActivity.class);
                                startActivity(intent3);
                            }
                            showToast(js.getString("msg"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void caogaofabu(String time) {
        if (!UserManageBean.isLogin(CreadChapterOkActivity.this)) {
            return;
        }
        OkHttpUtils.post(HttpManager.IP + "/chapter-update")

                .params("id", bookBean.getId())
                .params("bookId", bookBean.getBookId())
                .params("chapterTitle", bookBean.getChapterTitle())
                .params("volumeId", bookBean.getVolumeId())
                .params("chapterContent", chapter)
                .params("releaseTime", time)
                .params("chapterIsvip", String.valueOf(chapterIsVip))
                .params("whetherPublic", "2")
                .params("chapterLength", StringTool.getChapterTextLength(chapter))
                .params("authorWords", bookBean.getAuthorWords())
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog == null) {
                            noBackgLodDialog = new NoBackgLodDialog(CreadChapterOkActivity.this, true);
                        }
                        if (!noBackgLodDialog.isShowing()) {
                            noBackgLodDialog.show();
                        }
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog != null && noBackgLodDialog.isShowing()) {
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                SettingManager.getInstance().saveNewChapterNum();
                                showToast(js.getString("msg"));
                                CreatChapterSettingManager.getInstance().saceIsShangchuan(bookBean.getBookId(), 1);
                                CreatChapterSettingManager.getInstance().saveCreatobject(bookBean.getBookId(), null);
                                if (bookBean.getIsCaogao() == 1) {
                                    setResult(2);
                                    goBack();
                                }
                                else {
                                    setResult(2);
                                    goBack();
                                }
                            }else if (js.getInt("returnCode") == 400){
                                showToast(js.getString("msg"));
                                Intent intent3=new Intent(CreadChapterOkActivity.this,LoginActivity.class);
                                startActivity(intent3);
                            }
                            else {
                                showToast(js.getString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void tofabu(String time) {
        if (!UserManageBean.isLogin(CreadChapterOkActivity.this)) {
            return;
        }
        OkHttpUtils.post(HttpManager.IP + "/chapter-creates")

                .params("bookId", bookBean.getBookId())
                .params("bookTitle", bookBean.getBookTitle())
                .params("chapterTitle", bookBean.getChapterTitle())
                .params("chapterContent", chapter)
                .params("releaseTime", time)
                .params("chapterIsvip", String.valueOf(chapterIsVip))
                .params("volumeId", bookBean.getVolumeId())
                .params("whetherPublic", "0")
                .params("chapterLength", StringTool.getChapterTextLength(chapter))
                .params("authorWords", bookBean.getAuthorWords())
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog == null) {
                            noBackgLodDialog = new NoBackgLodDialog(CreadChapterOkActivity.this, true);
                        }
                        if (!noBackgLodDialog.isShowing()) {
                            noBackgLodDialog.show();
                        }
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog != null && noBackgLodDialog.isShowing()) {
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                SettingManager.getInstance().saveNewChapterNum();
                                showToast(js.getString("msg"));
                                CreatChapterSettingManager.getInstance().saceIsShangchuan(bookBean.getBookId(), 1);
                                if (bookBean.getIsCaogao() == 1) {
                                    goBack();
                                } else {
                                    setResult(2);
                                    goBack();
                                }

                            }else if (js.getInt("returnCode") == 400){
                                Intent intent3=new Intent(CreadChapterOkActivity.this,LoginActivity.class);
                                startActivity(intent3);
                                showToast(js.getString("msg"));
                            }
                            else {
                                showToast(js.getString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
